'use strict';

const Response = require('./response');
const iconvLite = require('iconv-lite');

class JsonResponse extends Response {

    constructor(response, options) {
        super(response, options);

        this._doEncoding(options);

        this.body = JSON.parse(this.body);
    }

    _doEncoding(options) {
        if (options.forceUTF8) {
            var charset = this.charset;

            if (charset !== 'utf-8' && charset !== 'ascii') {
                // convert response.body into 'utf-8' encoded buffer
                this.body = iconvLite.decode(this.body, charset);
            }
        }

        if (typeof this.body === 'object' && Buffer.isBuffer(this.body)) {
            this.body = new String(this.body);
        } else if (typeof this.body === 'object') {
            this.body = JSON.stringify(this.body);
        }
    }

    getJSON() {
        return this.body;
    }

}

module.exports = JsonResponse;